<template>
  <el-container class="friends_tas">
    <el-main>
      <el-card shadow="never" class="selectCard searchColumn">
        <el-form label-position="right" label-width="6rem">
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="欢迎语：">
                <el-input v-model="searchParams.content" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8" style="float: right;">
              <search-button :default-params="searchParams" @refreshParams="refreshParams" @getList="getEmployeeList1" />
            </el-col>
          </el-row>

        </el-form>
      </el-card>
      <el-card shadow="never" class="commercia-tenant-list-title tableCard">
        <vxe-toolbar :refresh="{query: getList}">
          <template v-slot:buttons>
            <el-button type="primary" icon="el-icon-plus" size="small" @click="openModal('', 1, false)">新增</el-button>
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTable"
          border
          resizable
          show-overflow
          highlight-hover-row
          :loading="loading"
          :auto-resize="true"
          :data="activitiesList"
          width
          max-height="500"
          :print-config="{}"
          header-align="center"
        >
          <vxe-table-column type="seq" align="center" width="50" title=" " />
          <vxe-table-column field="content" title="欢迎语" min-width="220" />
          <vxe-table-column field="syncStatusDesc" width="80" align="center" title="同步状态" />
          <vxe-table-column field="statusDesc" width="80" align="center" title="启用状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" :inactive-value="0" :active-value="1" active-text inactive-text @change="changeState(scope)" />
            </template>
          </vxe-table-column>
          <vxe-table-column title="操作" fixed="right" width="180" align="center" slots="default">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="openModal(scope.row.id, 2, true)">查看</el-button>
              <el-button v-if="scope.row.status != 1" type="text" size="mini" @click="openModal(scope.row.id, 2, false)">编辑</el-button>
              <el-button v-if="scope.row.status != 1" type="text" size="mini" @click="del(scope.row.id)">删除</el-button>
              <el-button type="text" size="mini" @click="syncToWxCp(scope.row.id)">同步</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
          :current-page.sync="tableCurrentPage"
          :page-size.sync="pageSize"
          :total="total"
          :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          @page-change="getList()"
        />
      </el-card>
    </el-main>
    <el-dialog v-if="dialogVisible" width="55%" title="信息编辑" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form ref="ruleForm" :model="params" :rules="rules" label-width="6rem">
        <el-row :gutter="40">
          <el-col :span="24">
            <el-form-item prop="channelId" label="渠道：">
              <el-select v-model="params.channelId">
                <el-option v-for="item in channelList" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="tagsName" label="欢迎语：">
              <div style="display: inline-block;width: 100%;" class="inputDeep">
                <div v-if="!diabledEdit" style="display: flex;justify-content: right; ">
                  <div style="justify-content: right;padding-left: 5px;">
                    <span slot="reference" style="font-size: 12px; cursor: pointer;"><i class="el-icon-s-custom" @click="insertTemplateParam">添加昵称</i></span>
                  </div>
                </div>
                <el-input id="templateContent" v-model="params.content" type="textarea" :rows="12" maxlength="1000" show-word-limit resize="none" :disabled="diabledEdit" />
                <div style="display: inline-block;">
                  <div style="display: flex; justify-content: flex-start;">
                    <div v-if="!diabledEdit" style="display: flex;">
                      <el-popover placement="top" width="380" trigger="click">
                        <div class="function-cont" style="margin-left: 10px; justify-content: center;">
                          <el-row :gutter="10">
                            <el-col :span="4">
                              <div style="justify-content: center;display: inline-block;" @click="uploadImage">
                                <i class="el-icon-picture" style="cursor: pointer;position: relative;padding-left: 3px;" /><div style="font-size: 12px; cursor: pointer;">图片</div>
                              </div>
                            </el-col>
                            <el-col :span="4" :offset="1">
                              <div class="infoItem_editor_add" @click="uploadVideo">
                                <i class="el-icon-document" style="cursor: pointer;position: relative;padding-left: 3px;" /><div style="font-size: 12px;cursor: pointer;">视频</div>
                              </div>
                            </el-col>
                            <el-col :span="4" :offset="1">
                              <div class="infoItem_editor_add" @click="uploadFile">
                                <i class="el-icon-goods" style="cursor: pointer;position: relative;padding-left: 3px;" /><div style="font-size: 12px;cursor: pointer;">文件</div>
                              </div>
                            </el-col>
                            <el-col :span="4" :offset="1" @click="uploadLink">
                              <div class="infoItem_editor_add">
                                <i class="el-icon-sell" style="cursor: pointer;position: relative;padding-left: 3px;" /><div style="font-size: 12px;cursor: pointer;">链接</div>
                              </div>
                            </el-col>
                            <el-col :span="5" @click="uploadWxMa">
                              <div class="infoItem_editor_add">
                                <i class="el-icon-chat-dot-round" style="cursor: pointer;position: relative;padding-left: 10px;" /><div style="font-size: 12px;cursor: pointer;">小程序</div>
                              </div>
                            </el-col>
                          </el-row>
                        </div>
                        <span slot="reference" style="font-size: 10px;color: cornflowerblue; cursor: pointer;"><i class="el-icon-plus">添加:图片/视频/文件/图文/小程序</i></span>
                      </el-popover>
                    </div>
                    <div class="function-cont" style="display: block; justify-content: right; margin-left: 10px; text-align: right;"><span style="font-size: 10px;">(备注：最多9个附件)</span></div>
                  </div>
                  <div class="file-url">
                    <div v-for="(item, index) in params.attachements" :key="index" class="fz20 file-url-cont">
                      <div>
                        <span>{{ index+1 }}.</span>
                        <span @click="downFileClick(item.filePath)">{{ item.fileName }}</span>
                        <i v-if="!diabledEdit" class="el-icon-close" @click="closeFileClick(index)" />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
    <ImgSource ref="imgSelect" :max="99999" @getUrl="getReturnPicsUrl" />
    <VideoSource ref="videoSelect" :max="99999" @getUrl="getReturnVideoUrl" />
    <DocSource ref="docSelect" :max="99999" @getUrl="getReturnDocUrl" />
  </el-container>
</template>

<script>
import { syncFansWelcomeToWxCp, delFansChannelWelcome, getFansChannelWelcomePageList, addFansChannelWelcome, modifyFansChannelWelcome, viewFansChannelWelcome, changeFansChannelWelcomeStatus, getCopChannelList } from '@/api/cop/fans'
import SearchButton from '@/components/SearchButton'
import ImgSource from './imgSelect'
import VideoSource from './videoSelect'
import DocSource from './docSelect'
export default {
  components: {
    SearchButton,
    ImgSource,
    VideoSource,
    DocSource
  },
  data() {
    return {
      activitiesList: [],
      channelList: [],
      loading: false,
      searchParams: {
        content: ''
      },
      tableCurrentPage: 1,
      pageSize: 20,
      total: 0,
      params: {
        content: '',
        attachements: []
      },
      dialogVisible: false,
      diabledEdit: true,
      rules: {
        content: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      parentId: '',
      type: 1 // 1 添加 2修改
    }
  },
  created() {
    this.getList()
    this.getChannelList()
  },
  methods: {
    uploadVideo() {
      this.$refs.videoSelect.dialog = true
    },
    uploadFile() {
      this.$refs.docSelect.dialog = true
    },
    uploadLink() {

    },
    uploadWxMa() {

    },
    uploadImage() {
      this.$refs.imgSelect.dialog = true
    },
    getReturnPicsUrl(selectedPics) {
      if (this.params.attachements.length >= 9) {
        alert('最多可以添加9个附件，不能再增加了')
        return false
      }
      selectedPics.forEach(url => {
        const fullUrl = url.split('/')

        const fileName = fullUrl[fullUrl.length - 1]
        const formItem = this.params.attachements.find(dd => dd.fileName === fileName)
        if (formItem === null || formItem === undefined) {
          this.params.attachements.push({ filePath: url, fileName: fileName, msgType: 'image' })
        }
      })
    },
    getReturnDocUrl(url) {
      if (this.params.attachements.length >= 9) {
        alert('最多可以添加9个附件，不能再增加了')
        return false
      }
      if (url) {
        const fullUrl = url.split('/')
        const fileName = fullUrl[fullUrl.length - 1]
        const formItem = this.params.attachements.find(dd => dd.fileName === fileName)
        if (formItem === null || formItem === undefined) {
          this.params.attachements.push({ filePath: url, fileName: fileName, msgType: 'file' })
        }
      }
    },
    getReturnVideoUrl(url) {
      if (this.params.attachements.length >= 9) {
        alert('最多可以添加9个附件，不能再增加了')
        return false
      }
      if (url) {
        const fullUrl = url.split('/')
        const fileName = fullUrl[fullUrl.length - 1]
        const formItem = this.params.attachements.find(dd => dd.fileName === fileName)
        if (formItem === null || formItem === undefined) {
          this.params.attachements.push({ filePath: url, fileName: fileName, msgType: 'video' })
        }
      }
    },
    closeFileClick(i) {
      this.$delete(this.params.attachements, i)
    },
    downFileClick(filePath) {
      window.open(filePath, '_blank')
    },
    syncToWxCp(id) {
      this.$confirm('确定要从企业微信同步新客欢迎语, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        syncFansWelcomeToWxCp({ id }).then(res => {
          if (res) {
            this.$message.info('正在从企业微信同步新客欢迎语，请稍候刷新！')
            this.$nextTick(() => {
              this.getList()
            })
          }
        })
      }).catch(() => {
        this.$message.info('取消操作')
      })
    },
    openModal(id, type, bool) {
      this.diabledEdit = bool
      this.operationType = type
      this.dialogVisible = true
      if (type === 2) {
        viewFansChannelWelcome({ id })
          .then(response => {
            if (response) {
              this.params = response
              this.params.attachements = response.attachements
            }
          })
      } else {
        this.params.content = ''
        this.params.attachements = []
      }
    },
    getChannelList() {
      getCopChannelList({}).then(response => {
        if (response) {
          this.channelList = response
        }
      })
    },
    getList() {
      getFansChannelWelcomePageList({
        pageNum: this.tableCurrentPage,
        pageSize: this.pageSize,
        ... this.searchParams
      }).then(response => {
        if (response) {
          this.activitiesList = response
          this.total = response.total
        }
      })
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.operationType === 1) {
            addFansChannelWelcome(this.params).then(response => {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            modifyFansChannelWelcome(this.params).then(response => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    del(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delFansChannelWelcome({ id }).then(response => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    changeState(scope) {
      this.activitiesList[scope.seq - 1].status = scope.row.status === 1 ? 0 : 1
      changeFansChannelWelcomeStatus({
        id: scope.row.id,
        status: scope.row.status === 1 ? 0 : 1
      }).then(response => {
        this.activitiesList[scope.seq - 1].status = scope.row.status === 1 ? 0 : 1
        this.$message.success(scope.row.status === 0 ? '禁用成功' : '启用成功')
      })
    },
    insertTemplateParam() {
      const key = '%NICKNAME%'
      const elInput = document.getElementById('templateContent')
      const startPos = elInput.selectionStart

      const endPos = elInput.selectionEnd

      if (startPos === undefined || endPos === undefined) {
        elInput.value = key
      } else {
        const txt = elInput.value
        const result = txt.substring(0, startPos) + key + txt.substring(endPos)
        elInput.value = result
      }
      elInput.$nextTick(() => {
        elInput.focus()
        elInput.selectionStart = startPos + key.length
        elInput.selectionEnd = startPos + key.length
      })
    }
  }
}
</script>

<style lang="scss">
.friends_tas {
 .function-cont{
    display: inline-flex;
    position: relative;
    flex-direction: row;
    flex-wrap: wrap;
    padding-left: 10px;
    justify-content: space-between;
     >div{
      width: 60px;
      display: inline-flex;
      text-align: center;
      justify-content: center;
      align-content: center;
      padding-bottom: 15px;
      line-height: 35px;
      border: 1px solid grey;
      >div{
        &:first-child{
          background: lightsteelblue;
          padding: 10px;
          cursor: pointer;
          margin-left: 10px;
          border: 1px solid grey;
          font-size: 10px;
          &::before{
            font-size: 40px;
            justify-content: center;
            color: #fff;
          }
        }
        &:last-child{
          cursor: pointer;
          justify-content: center;
          font-size: 14px;
        }
      }
     }
  }
  .inputDeep {
    :deep(.el-textarea__inner) {
      box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
      resize: none;
      cursor: default;
    }
  }
  .infoItem_editor_add {
      display: inline-block;
      padding-bottom: 1px;
      flex-direction: column;
      width: 80px;
      height: 80px;
      margin-left: 5px;
      border: 1px solid #dfe1e3;
      justify-content: center;
      float: right;
      text-align: center;
      align-items: center;
      align-content: center;
      font-size: 12px;
      cursor: pointer;
      margin-right: 5px;
      overflow: hidden;
      position: relative;
  }
  .info-form>>>.el-form-item label:after {
    content: " ";
    display: inline-block;
    width: 100%;
  }
  .info-form>>>.el-form-item__label {
    text-align: center;
    vertical-align: middle;
  }
  .info-form>>>.el-form-item.is-required .el-form-item__label:before {
    content: none !important;
  }
  .file-url{
    display: flex;
    line-height: 18px;
    flex-direction: column;
    .file-url-cont{
      div{
        padding: 2px;
        display: inline-block;
        cursor: pointer;
        span{
          margin-left: 10px;
          margin-right: 10px;
          float: left;
        }
        i {
          float: left;
          display: block;
          padding-top: 1px;
        }
        &:hover{
          background: #f5f7fa;
          i{
            display: block;
          }
        }
      }
   }
  }
}
</style>
